package com.vs.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.vs.common.InvalidUserException;
import com.vs.common.SessionKeys;
import com.vs.dao.ExpensesTypeOperation;
import com.vs.dao.LaborTypeOperation;
import com.vs.dao.ProjectOperations;
import com.vs.dao.Security;
import com.vs.model.CustomMessage;
import com.vs.model.LoginForm;
import com.vs.model.User;
import com.vs.util.Constants;

public class LoginAction extends Action {
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String next;
		LoginForm loginForm = (LoginForm) form;
		// System.out.println("usename=" + loginForm.getUsername());
		// System.out.println("pass=" + loginForm.getPassword());

		Constants.log.debug(loginForm);
		ArrayList<CustomMessage> customErrors = new ArrayList<CustomMessage>();
		
		Security security = new Security();
		
		try {
			User user = security.validateUser(loginForm);
			if (user != null) {
				next = "success";

				// save data in session now
				HttpSession session = request.getSession();
				session.setAttribute(SessionKeys.CURRENT_USER, user);

				session.setAttribute(SessionKeys.EXPENSE_TYPES,
						new ExpensesTypeOperation().getExpenseTypeLOV());

				session.setAttribute(SessionKeys.PROJECT_LOV,
						new ProjectOperations().getProjectLOV());

				session.setAttribute(SessionKeys.LABOR_TYPES,
						new LaborTypeOperation().getLaborTypeLOV());

			} else {
				next = "error";
				CustomMessage info = new CustomMessage();
				info.setMessageLevel(Constants.ERROR);
				info.setMessageText("Incorrect username/password");
				customErrors.add(info);
			}
		} catch (InvalidUserException e) {
			next = "error";
			CustomMessage info = new CustomMessage();
			info.setMessageLevel(Constants.ERROR);
			info.setMessageText(e.getMessage());
			customErrors.add(info);
		}
		
		request.setAttribute("customErrors", customErrors);
		return mapping.findForward(next);
	}
}
